package lukeer.fencing;

import java.io.*;

/**
 * Class used in Part A of project, loads board into memory and creates a board object.
 *
 * User: Luke Richardson lukeer, Wafa M'Barek wmbarek
 * Date: 09/08/12
 * Time: 05:56
 */

public class Input implements csproj.fencing.Piece {
    private BufferedReader br;
    private Board board;

    /**
     * Constructor attempts to load a file of name fileName, given an absolute path, or if relative if in the
     * TestFiles folder.
     *
     * @param fileName The name of a test file
     * @throws FileNotFoundException Thrown if the path to the file is invalid
     */
    public Input(String fileName) throws FileNotFoundException {
        FileInputStream fstream = new FileInputStream(fileName);
        DataInputStream in = new DataInputStream(fstream);
        br = new BufferedReader(new InputStreamReader(in));
        try {
            board = readInput();
        } catch (IOException e) {
            System.err.println("Error reading file " + fileName);
        }
    }

    public Input() {
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            board = readInput();
        } catch (IOException e) {
            System.err.println("Error reading file ");
        }
    }

    /**
     * Parses board input and creates a board object with an input board configuration
     *
     * @return A board object that contains the configuration of an input stream
     * @throws IOException An exception is thrown if the board configuration is not correct
     */
    Board readInput() throws IOException {
        int size = Integer.parseInt(br.readLine());
        try {
            board = new Board(size);
        } catch (FencingException e) {
            e.printStackTrace();
        }
        String strLine;

        for (int i = 0; i < size * 2 + 1; i++) {
            strLine = br.readLine();
            for (int j = 0; j < strLine.length(); j++) {

                if (strLine.charAt(j) == '=') {
                    board.getPiece(i / 2, j / 2).setHFence();
                }
                if (strLine.charAt(j) == '#') {
                    board.getPiece(i / 2, j / 2 / 2).setVFence();
                }
                if (strLine.charAt(j) == 'B') {
                    board.getPiece(i / 2, (j / 2 - 1) / 2).setType(BLACK);
                }
                if (strLine.charAt(j) == 'W') {
                    board.getPiece(i / 2, (j / 2 - 1) / 2).setType(WHITE);
                }
            }
        }
        return board;
    }

    public Board getBoard() {
        return board;
    }

}

